﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iSun.Web.UI.Controls;
using iSun.BLL.Base;
using iSun.Common;
using iSun.BLL;
using iSun.DBModule;
using iSun.EHR.Library;
using iSun.TR.Library;
using iSun.TR.Bussiness;
using commonDal = iSun.WebApp.Extend.Common;
using System.Text;
using System.Data;
using iSun.SYS.Bussiness.Message;
using iSun.SYS.Library;
using iSun.CRM.Library;
using iSun.CRM.Bussiness;
using System.Collections;
using iSun.WebApp.Extend.Common;
namespace iSun.WebApp.Extend.AjaxData
{

    public partial class DataProcessin : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string action = this.GetStringFromQueryString("action", "");
            switch (action.ToLower())
            {
                case "get":
                    GetData();
                    break;
                case "save":
                    Save();
                    break;
                case "update":
                    Update();
                    break;
                case "delete":
                    Delete();
                    break;
                case "import":
                    Import();
                    break;
                case "cancel":
                    Cancel();
                    break;
                default:
                    GetData();
                    break;
            }
        }
        private void Cancel()
        {  
            string strEntity = this.GetStringFromQueryString("entity", "");
            switch (strEntity.ToLower())
            {
                case "datemployee":
                    //取消用户区域权限设置
                    cancelAreaUserSet();
                    break;
            }
        }
        //取消用户区域权限设置
        private void cancelAreaUserSet()
        {
            try
            {
                string[] users = ZXContext.Request.Form["jsonUsers"].ToString().Split(',');
                BaseBussnies<DatEmployee> binstance = new BaseBussnies<DatEmployee>();
                DatEmployee employee = new DatEmployee();
                binstance.entity = employee;
                if (users.Length > 0)
                {
                    for (int i = 0; i < users.Length; i++)
                    {
                        employee = binstance.GetEntityById<DatEmployee>(Guid.Parse(users[i].ToString()));
                        employee.DeptIds ="";
                        binstance.Update(employee);

                    }

                }
                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        //导出报表
        private void Import()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strCondition = this.GetStringFromQueryString("condition", "");
            string title = this.GetStringFromQueryString("title", "");
            strCondition = Server.UrlDecode(strCondition);
            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            if (entity == null)
            {
                entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            }
            //得到要导出的数据源
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            DataTable dt = string.IsNullOrEmpty(strCondition) ? bll.GetDataTableByCondition("1=1") : bll.GetDataTableByCondition(strCondition);

            //得到要导出的字段名
            StringBuilder sbTitles = new StringBuilder();
            StringBuilder sbFields = new StringBuilder();
            BaseBussnies dtBll = new BaseBussnies();
            IList<DataListTemplate> _list = dtBll.GetEntitys<DataListTemplate>(" EntityName='" + strEntity + "'");
            _list = _list.OrderBy(p => p.iOrder).ToList();
            foreach (DataListTemplate _template in _list)
            {
                if (_template.THCaption.ToLower().IndexOf("id") == -1)
                {
                    sbTitles.Append(_template.THCaption + ",");
                    sbFields.Append(_template.Field + ",");
                }

            }
            string[] titles = sbTitles.ToString().TrimEnd(',').Split(',');
            string[] fields = sbFields.ToString().TrimEnd(',').Split(',');
            commonDal.ExcelHelper eh = new commonDal.ExcelHelper(titles, fields, dt);
            eh.DataToCSV(Server.UrlDecode(title));
        }

        /// <summary>
        /// 得到消息列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private void GetMessageList()
        {

            string state = this.GetStringFromQueryString("state", "");
            if (state == "0" || state == "3")
            {
                //未查看
                BV_MessagePool messageMrg1 = new BV_MessagePool();
                int i = 0;
                if (state == "3")
                {
                    SYS.Library.V_MessagePool UnreadMessages = messageMrg1.GetNewestUnreadMessage(this.UserId);
                    if (UnreadMessages != null)
                    {
                        HttpContext.Current.Response.Write(UnreadMessages.MPoolID.ToString());
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("0");
                    }
                }
                else
                {
                    IList<SYS.Library.V_MessagePool> AllMessages = messageMrg1.GetUnreadSysMessages(this.UserId);
                    StringBuilder sb = new StringBuilder();

                    sb.Append("<table border='1px' cellspacing='0' cellpadding='0' width='100%' id='tb_messageList'>");
                    sb.Append("<thead>");
                    sb.Append("<tr>");
                    sb.Append("<th>消息类型</th><th>发送人</th><th>消息主题</th><th >发送时间</th>");
                    sb.Append("</tr>");
                    sb.Append("</thead>");
                    sb.Append("<tbody>");
                    if (AllMessages != null && AllMessages.Count > 0)
                    {
                        foreach (V_MessagePool message in AllMessages)
                        {
                            if (i % 2 != 0)
                            {
                                sb.Append("<tr class='odd' onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'odd');\"  onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");

                            }
                            else
                            {
                                sb.Append("<tr onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'');\" onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");
                            }
                            i++;
                            if (i > 8) continue;//只显示8条记录
                            string tds = "<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>";

                            //显示消息类型
                            string type = "";
                            switch (message.MessageType)
                            {
                                case "0": type = "系统消息";
                                    break;
                                case "1": type = "Email";
                                    break;
                                case "2": type = "手机短信";
                                    break;
                                case "3": type = "QQ";
                                    break;
                            }
                            //显示时间
                            string dtStr = " <font color=\"#999999\">{0}</font>";
                            dtStr = String.Format(dtStr, message.SendTime.ToString("yyyy年MM月dd日"));
                            tds = string.Format(tds, type, message.AddUserName == "" ? "&nbsp&nbsp" : message.AddUserName, message.Title, dtStr);
                            sb.Append(tds);
                            sb.Append("</tr>");
                        }

                    }
                    else
                    {
                        sb.Append("<tr><td colspan=4 class='odd'>没有消息可显示</td></tr>");
                    }
                    sb.Append("</tbody>");
                    sb.Append("</table>");
                    HttpContext.Current.Response.Write(sb.ToString());
                }
            }
            else if (state == "1")
            {
                //已查看
                BV_HistoryMessagePool target = new BV_HistoryMessagePool(); // TODO: 初始化为适当的值
                IList<SYS.Library.V_HistoryMessagePool> ilist = target.GetReceiverSysMessages(this.UserId);
                StringBuilder sb = new StringBuilder();

                sb.Append("<table border='1px' cellspacing='0' cellpadding='0' width='100%' id='tb_messageList'>");
                sb.Append("<thead>");
                sb.Append("<tr>");
                sb.Append("<th>消息类型</th><th>发送人</th><th>消息主题</th><th >发送时间</th>");
                sb.Append("</tr>");
                sb.Append("</thead>");
                sb.Append("<tbody>");
                int i = 0;
                if (ilist != null && ilist.Count > 0)
                {
                    foreach (V_HistoryMessagePool message in ilist)
                    {
                        if (i % 2 != 0)
                        {
                            sb.Append("<tr class='odd' onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'odd');\"  onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");

                        }
                        else
                        {
                            sb.Append("<tr onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'');\" onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");
                        }
                        i++;
                        if (i > 8) continue;//只显示8条记录
                        string tds = "<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>";

                        //显示消息类型
                        string type = "";
                        switch (message.MessageType)
                        {
                            case "0": type = "系统消息";
                                break;
                            case "1": type = "Email";
                                break;
                            case "2": type = "手机短信";
                                break;
                            case "3": type = "QQ";
                                break;
                        }
                        //显示时间
                        string dtStr = " <font color=\"#999999\">{0}</font>";
                        dtStr = String.Format(dtStr, message.SendTime.ToString("yyyy年MM月dd日"));
                        tds = string.Format(tds, type, message.AddUserName == "" ? "&nbsp&nbsp" : message.AddUserName, message.Title, dtStr);
                        sb.Append(tds);
                        sb.Append("</tr>");
                    }

                }
                else
                {
                    sb.Append("<tr><td colspan=4 class='odd'>没有消息可显示</td></tr>");
                }
                sb.Append("</tbody>");
                sb.Append("</table>");
                HttpContext.Current.Response.Write(sb.ToString());
            }
            else if (state == "")
            {
                //全部
                BV_AllMessage target = new BV_AllMessage(); // TODO: 初始化为适当的值
                IList<SYS.Library.V_AllMessage> ilist = target.GetAllSysMessages(this.UserId);
                StringBuilder sb = new StringBuilder();

                sb.Append("<table border='1px' cellspacing='0' cellpadding='0' width='100%' id='tb_messageList'>");
                sb.Append("<thead>");
                sb.Append("<tr>");
                sb.Append("<th>消息类型</th><th>发送人</th><th>消息主题</th><th >发送时间</th>");
                sb.Append("</tr>");
                sb.Append("</thead>");
                sb.Append("<tbody>");
                int i = 0;
                if (ilist != null && ilist.Count > 0)
                {
                    foreach (V_AllMessage message in ilist)
                    {
                        if (i % 2 != 0)
                        {
                            sb.Append("<tr class='odd' onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'odd');\"  onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");

                        }
                        else
                        {
                            sb.Append("<tr onmouseover=\"ChangeClass(this,'selected');\" onmouseout=\"ChangeClass(this,'');\" onclick=\"javascript:ShowMsg('" + message.MPoolID + "','" + state + "')\">");
                        }
                        i++;
                        if (i > 8) continue;//只显示8条记录
                        string tds = "<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td>";

                        //显示消息类型
                        string type = "";
                        switch (message.MessageType)
                        {
                            case "0": type = "系统消息";
                                break;
                            case "1": type = "Email";
                                break;
                            case "2": type = "手机短信";
                                break;
                            case "3": type = "QQ";
                                break;
                        }
                        //显示时间
                        string dtStr = " <font color=\"#999999\">{0}</font>";
                        dtStr = String.Format(dtStr, message.SendTime.ToString("yyyy年MM月dd日"));
                        tds = string.Format(tds, type, message.AddUserName == "" ? "&nbsp&nbsp" : message.AddUserName, message.Title, dtStr);
                        sb.Append(tds);
                        sb.Append("</tr>");
                    }

                }
                else
                {
                    sb.Append("<tr><td colspan=4 class='odd'>没有消息可显示</td></tr>");
                }
                sb.Append("</tbody>");
                sb.Append("</table>");
                HttpContext.Current.Response.Write(sb.ToString());
            }

        }
        private void GetData()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            switch (strEntity)
            {
                case "V_HistoryMessagePool": GetMessageList();
                    break;
                case "DatEmployee": GetUserArea();
                    break;
                case "DatPositons": GetDatPositions();
                    break;
                case "V_UserEmp": GetDeptUser();
                    break;
                case "Announce": GetAnnounce();
                    break;
                default: GetCommonData();
                    break;
            }



        }
        //得到公告
        private void GetAnnounce()
        {
            BaseBussnies bll = new BaseBussnies();
            BVuseremp buser = new BVuseremp();
            V_UserEmp user = buser.getUserInfoByUserId(this.UserId);
           // IList<V_Announce> _list = bll.GetEntitys<V_Announce>("DeptID='" + user.DeptID + "'order by addtime desc");

            IList<Announce> _list = bll.GetEntitys<Announce>("1=1 order by AddTime desc");
         
            StringBuilder sb = new StringBuilder();
            if (_list != null && _list.Count > 0)
            {
                int i = 0;
                foreach (Announce announce in _list)
                {
                    if (++i > 10) continue;//只显示6条记录

                    //显示时间
                    string dtStr = " <font color=\"#999999\">{0}</font>";
                    dtStr = String.Format(dtStr, announce.AddTime.ToString("yyyy年MM月dd日 HH:mm dddd"));
                    //显示是否置顶
                    string subject = announce.Subject;
                    string sendName = announce.AddUserName;
                    if (announce.IsOnTop)
                    {
                        //subject+="[置顶]";
                    }

                    sb.Append(dtStr);
                    sb.Append("<br>");
                    sb.Append("<img align='absMiddle' src='../../Images/arrow11.gif' width='9' height='9'>");
                    sb.Append(" <a href='#' onclick=\"javascript:ShowAnnounce('" + announce.ID.ToString() + "')\" >");
                    //Lb_DeptAnnounceList.Text+=Staple.PadString(subject,10,true);
                    sb.Append(Staple.PadString(subject, 10, true));
                    sb.Append(" 【");
                    sb.Append(announce.AddUserName);
                    sb.Append("】");
                    sb.Append("</a><br>");
                }
            }
            HttpContext.Current.Response.Write(sb.ToString());
        }
        private void GetDeptUser()
        {
            try
            {
                string deptId = this.GetStringFromQueryString("deptId", "");
                BaseBussnies bll = new BaseBussnies();
                IList<V_UserEmp> _list = bll.GetEntitys<V_UserEmp>("DeptID='" + deptId + "'");
                if (_list != null && _list.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (V_UserEmp userEmp in _list)
                    {
                        sb.Append(userEmp.UserID.ToString());
                        sb.Append(",");
                        sb.Append(userEmp.Name + " [" + userEmp.DeptName + "]");
                        sb.Append("~");
                    }
                    HttpContext.Current.Response.Write(sb.ToString());
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void GetUserArea()
        {
            try
            {
                //得到部门ID
                string empId = this.GetStringFromQueryString("EmpId", "");
                 BaseBussnies<DatEmployee> binstance = new BaseBussnies<DatEmployee>();
                 BaseBussnies<DatDepartment> deptMgr = new BaseBussnies<DatDepartment>();
                DatEmployee employee = new DatEmployee();
                binstance.entity = employee;
                employee = binstance.GetEntityById<DatEmployee>(Guid.Parse(empId));
                string[] deptIds = employee.DeptIds.Split(',');
                StringBuilder sb = new StringBuilder();
                if (deptIds.Length > 0)
                {
                    DatDepartment dept = new DatDepartment();
                    deptMgr.entity = dept;
                    foreach (string deptId in deptIds)
                    {
                        if (!string.Empty.Equals(deptId))
                        {
                            dept = deptMgr.GetEntityById<DatDepartment>(Guid.Parse(deptId));
                            if (dept != null)
                            {
                                sb.Append(dept.DeptID.ToString());
                                sb.Append(",");
                                sb.Append(dept.DeptName);
                                sb.Append("~");

                            }
                        }
                      
                    }
                }
                HttpContext.Current.Response.Write(sb.ToString());
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void GetDatPositions()
        {
            try
            {
                //得到部门ID
                string deptId = this.GetStringFromQueryString("deptId", "");
                BaseBussnies bll = new BaseBussnies();
                IList<DatPositions> _list = bll.GetEntitys<DatPositions>("DeptID='" + deptId + "'");
                if (_list != null && _list.Count > 0)
                {
                    DatPositions de = _list[0];
                    HttpContext.Current.Response.Write(de.DeptID);
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void GetCommonData()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strCondition = this.GetStringFromQueryString("condition", "");
            strCondition = Server.UrlDecode(strCondition);
            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            if (entity == null)
            {
                entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            }
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            IList<BaseEntity> list = string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
            if (list != null)
            {

                string strFormat = "{\"total\":" + list.Count().ToString() + ",\"rows\":[";
                string str = list.ToJSON().Replace("\n", "").Replace("\r", "").Replace("null", "");
                strFormat = strFormat + str + "]}";
                //strFormat = strFormat.Replace(new Regex("(^|[^\\\\])\\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\\"","$1new Date($2)");
                HttpContext.Current.Response.Write(strFormat);
            }
        }

        /// <summary>
        /// 保存用户角色
        /// </summary>
        private void Save()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string ids = "";
            ids = this.GetStringFromQueryString("ids", "");
            if (strEntity == "SysRoleFunction" )
            {
                ids = ZXContext.Request.Form[0].ToString();
            }
            string[] strIds = ids.Trim(',').Split(',');
            switch (strEntity)
            {
                case "SysUserRole":
                    SaveSysUserRole(strIds);
                    break;
                case "SysRoleFunction":
                    //SaveSysRoleFunction(strIds);
                    SaveSysRoleFunction(ids);
                    break;
                case "DatUser":
                    SavePassword(ids);
                    break;
                case "TrQuestionnaireSubject":
                    SaveTrQuestionnaireSubject(strIds);
                    break;
                case "CrmCustomerShare":
                    SaveShareCustomer(strIds);
                    break;
                case "TrActivityCourse":
                    SaveTrActivityCourse(strIds);
                    break;
                case "DatDepartment":
                    SaveDepartment();
                    break;
                case "TrSendQuestion":
                    SaveTrSendQuestion(strIds);
                    break;
                case "DatEmployee":
                    SaveEmployeeArea();
                    break;
                case "DatPositions":
                    SaveDatPositions(ids);
                    break;
                case "Announce":
                    SaveAnnounce();
                    break;


            }
        }
        private void SaveAnnounce()
        {
            try
            {

                string subject = ZXContext.Request.Form["txtSubject"].ToString();
                string files = ZXContext.Request.Files.Count.ToString();
                string ReceivedeptId = Request.QueryString["deptId"].ToString();
                string content = ZXContext.Request.Form["jsonDataContent"].ToString();
                ////业务处理类
                BaseBussnies Bbussness = new BaseBussnies();
                BVuseremp userMrg = new BVuseremp();
                int accLength = 0;
                // HttpFileCollection accfiles = ZXContext.Request.Files;
                //    if (accfiles.Count > 0)
                //    {
                //        for (int i = 0; i < accfiles.Count; i++)
                //        {
                //            HttpPostedFile accpostFile = accfiles[i];
                //            accLength += accpostFile.ContentLength;
                //            if (accLength > 5 * 1024 * 1024)
                //                ClientScript.RegisterStartupScript(this.GetType(), "msg", "<script language='javascript'>alert('附件超过5M！')</script>");

                //            //return;
                //        }
                //    }
                //公告主体
                Announce announce = new Announce();
                V_UserEmp userInfo = userMrg.getUserInfoByUserId(this.UserId);
                announce.ID = Guid.NewGuid();
                announce.Subject = subject;
                announce.Content = content;
                announce.AddUser = (Guid)this.UserId;
                announce.AddTime = DateTime.Now;
                announce.SendDeptId = userInfo == null ? Guid.Empty : userInfo.DeptID;
                announce.AddUserName = this.User.UName;
                announce.IsOnTop = false;
                //公告接收部门
                AnnounceDepartment ad = new AnnounceDepartment();
                ad.AnnounceID = announce.ID;
                ad.DeptID = new Guid(ReceivedeptId);
                //添加附件
                Accessories access = new Accessories();
                access.ID = Guid.NewGuid();
                access.AccessoriesType = 1;
                access.Attach = null;
                access.Path = Server.MapPath("upload\\" + ZXContext.Request.Form["UpAccessoriesFileName"].ToString());
                access.Name = ZXContext.Request.Form["UpAccessoriesFileName"].ToString();
                AnnounceAccessories annouceA = new AnnounceAccessories();
                annouceA.AnnounceID = announce.ID;
                annouceA.AttachID = access.ID;
                Bbussness.Insert(announce);
                Bbussness.Insert(ad);
                Bbussness.Insert(access);
                Bbussness.Insert(annouceA);

                //    //#region 选择接收部门
                //    //string[] Depts = txt_AreaHidden1.Value.Split(',');
                //    //if (Depts.Length > 0 && Depts[0].Length == 36)
                //    //{
                //    //    foreach (string us in Depts)
                //    //    {
                //    //        if (us.Length != 36) continue;
                //    //        //InfoPlatDepartment dept=IDM.GetByID(new Guid(us));
                //    //        //if(dept!=null)
                //    //        //{
                //    //        ad = new AnnounceDepartment();
                //    //        ad.Announce = announce;
                //    //        ad.DepartmentID = new Guid(us);
                //    //        ad.SchoolID = SchoolID;
                //    //        //}
                //    //        //announce.Departments.Add(dept);
                //    //        announce.AnnounceDepartments.Add(ad);
                //    //    }
                //    //}




                HttpContext.Current.Response.Write("1");
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        private void SaveEmployeeArea()
        {
            try
            {
                string areaIds = ZXContext.Request.Form["jsonDataContent"].ToString();
                string[] users = ZXContext.Request.Form["jsonUsers"].ToString().Split(',');
                BaseBussnies<DatEmployee> binstance = new BaseBussnies<DatEmployee>();
                DatEmployee employee = new DatEmployee();
                binstance.entity = employee;
                if (users.Length > 0)
                {
                    for (int i = 0; i < users.Length; i++)
                    {
                        employee = binstance.GetEntityById<DatEmployee>(Guid.Parse(users[i].ToString()));
                        employee.DeptIds = areaIds;
                        binstance.Update(employee);

                    }
                  
                }
                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void SaveDatPositions(string strIds)
        {
            BaseBussnies bll = new BaseBussnies();
            //获取部门下的所有职位
            try
            {
                string deptId = this.GetStringFromQueryString("deptId", "");
                DatDepartment deptEntity = new DatDepartment();
                bll.entity = deptEntity;
                deptEntity = bll.GetEntityBySqlComm<DatDepartment>("select * from DatDepartment where deptid='" + CSVHelper.FmSQL(deptId) + "'");
                string[] s = strIds.Split(',');
                for (int i = 0; i < s.Length; i++)
                {
                    DatPositions dps = new DatPositions();
                    dps.PTypeID = new Guid(s[i]);
                    dps.DeptID = deptId;
                    V_DatDutyInfo vdp = new V_DatDutyInfo();
                    bll.entity = vdp;
                    vdp = bll.GetEntityBySqlComm<V_DatDutyInfo>("select * from V_DatDutyInfo where Id='" + CSVHelper.FmSQL(s[i]) + "'");
                    dps.PositionName = (vdp == null || deptEntity == null) ? "找管理员" : deptEntity.DeptName + vdp.Name;
                    bll.entity = dps;
                    bll.Insert();
                }

                HttpContext.Current.Response.Write("1");
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("0");
            }

        }
        private void SaveDepartment()
        {
            try
            {
                BaseBussnies bll = new BaseBussnies();
                string deptName = this.GetStringFromQueryString("deptName", "");
                IList<DatDepartment> _list = bll.GetEntitys<DatDepartment>(" deptName='" + deptName + "'");
                if (_list != null && _list.Count > 0)
                {
                    HttpContext.Current.Response.Write("公司名已存在");
                }
                else
                {
                    //先添加公司
                    DatCompanyInfo companyinfo = new DatCompanyInfo();
                    companyinfo.CompanyName = deptName;
                    bll.entity = companyinfo;
                    bll.Insert();

                    DatDepartment dept = new DatDepartment();
                    dept.DeptName = deptName;
                    dept.AddUser = (Guid)this.UserId;
                    dept.AddTime = DateTime.Now;
                    dept.DeptPath = "@002";
                    dept.IsOutDepartment = 1;
                    bll.entity = dept;
                    bll.Insert();
                    HttpContext.Current.Response.Write("1");
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write("公司名已存在");
            }


        }
        /// <summary>
        /// 保存活动课程
        /// </summary>
        /// <param name="ids">课程ID列表</param>
        private void SaveTrActivityCourse(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                TrActivityCourse tr = new TrActivityCourse();
                bll.entity = tr;
                bll.delete("TrActivityID='" + pid + "'");
                if (Ids.Length == 1 && Ids[0] == "null")
                {
                    this.ZXContext.Response.Write("1");
                    return;
                }
                else
                {
                    for (int i = 0; i < Ids.Length; i++)
                    {
                        string sql = string.Format("Exec sp_AddTrActivityCourse '{0}','{1}','{2}',{3}",
                                                 new Guid(pid), new Guid(Ids[i]), new Guid(), i);
                        bll.RunSqlCommand(sql);
                    }
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }


        /// <summary>
        /// 保存用户角色
        /// </summary>
        /// <param name="ids">角色ID列表</param>
        private void SaveSysUserRole(string[] ids)
        {
            string userId = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                SysUserRole sr = new SysUserRole();
                bll.entity = sr;
                bll.delete("UserID='" + userId + "'");
                if (ids.Length == 1 && ids[0] == "null")
                {
                    this.ZXContext.Response.Write("1");
                    return;
                }
                else
                {
                    foreach (string id in ids)
                    {
                        sr.RoleID = new Guid(id);
                        sr.UserID = new Guid(userId);
                        sr.Remark = DateTime.Now.ToShortDateString();
                        bll.Insert();
                    }
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }
        //保存角色功能
        //private void SaveSysRoleFunction(string[] ids)
        private void SaveSysRoleFunction(string _id)
        {
            string[] ids = _id.TrimEnd(',').Split(',');
            string roldId = this.GetStringFromQueryString("roleid", "");
            string sql = "DELETE FROM SysRoleFunction Where RoleId='" + roldId + "' and  (not '" + _id + "' like '%'+cast(FunctionId as varchar(50))+'%') ";
            BaseBussnies bll = new BaseBussnies();
            SysRoleFunction sr = new SysRoleFunction();
            bll.entity = sr;
            bll.RunSqlCommand(sql);
            //bll.delete("RoleId ='" + roldId + "'");
            IList<SysRoleFunction> list = bll.GetEntitys<SysRoleFunction>("RoleId='" + roldId + "' and '" + _id + "' like '%'+cast(FunctionId as varchar(50))+'%'");
            if (!_id.Equals(""))
            {
                foreach (string id in ids)
                {

                    if (list == null)
                    {
                        sr.RoleID = new Guid(roldId);
                        sr.FunctionID = new Guid(id);
                        bll.Insert();
                    }
                    else
                    {
                        var _entity = list.Where(p => p.FunctionID == new Guid(id)).FirstOrDefault();
                        if (_entity == null)
                        {
                            sr.RoleID = new Guid(roldId);
                            sr.FunctionID = new Guid(id);
                            bll.Insert();
                        }
                    }
                }
            }
            HttpContext.Current.Response.Write("1");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        private void SavePassword(string userId)
        {
            string oldPwd = this.GetStringFromQueryString("old", "");
            string newPwd = this.GetStringFromQueryString("news", "");
            BaseBussnies bll = new BaseBussnies();
            DatUser du = new DatUser();
            bll.entity = du;
            string sql = string.Format("select * from DatUser where UserID='{0}' and Password='{1}'", userId, ExtendMethods.GetMd5Hash(oldPwd));
            object obj = bll.GetEntityBySqlComm(sql);
            if (obj != null)
            {
                string sqlUpdate = string.Format("update DatUser set Password='{0}' where UserID='{1}'", ExtendMethods.GetMd5Hash(newPwd), userId);
                if (bll.RunSqlCommand(sqlUpdate) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("修改密码失败!");
                }
            }
            else
            {
                HttpContext.Current.Response.Write("0");  //原始密码输入错误!请重新输入!
            }
        }
        /// <summary>
        /// 保存共享客户
        /// </summary>
        /// <param name="Ids">题目ID集合</param>
        private void SaveShareCustomer(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string toId = this.GetStringFromQueryString("toId", "");   //拥有客户的ID
            string strType = this.GetStringFromQueryString("type", "");  //类型 0：客户共享  1：客户分配时共享
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                CrmCustomerShare tr = new CrmCustomerShare();
                BCrmCustomerShare Bshare = new BCrmCustomerShare();
                DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                if (du == null)
                {
                    this.ZXContext.Response.Write("获取用户ID有误!");
                    return;
                }
                string result = string.Empty;
                result = Bshare.ExecDeleteCrmProc(new Guid(pid), du.UserID);
                if (result != "1")
                {
                    this.ZXContext.Response.Write("删除用户共享信息有误!");
                    return;
                }
                if (Ids.Length > 0)
                {
                    if (Ids.Length == 2 && Ids[1] == "22")  //部门所有人保存
                    {
                        if (strType == "0")
                        {
                            result = Bshare.ExecProc(new Guid(pid), new Guid(toId), new Guid(Ids[0].ToString()), du.UserID, 2);
                        }
                        else
                        {
                            result = Bshare.ExecProcCustomerInfo(new Guid(pid), new Guid(toId), new Guid(Ids[0].ToString()), du.UserID, 2);
                        }
                    }
                    else   //逐个个人保存
                    {
                        for (int j = 0; j < Ids.Length; j++)
                        {
                            if (Ids[j].Trim().Length == 0)
                            {
                                this.ZXContext.Response.Write(result);
                                return;
                            }
                            if (strType == "0")
                            {
                                result = Bshare.ExecProc(new Guid(pid), new Guid(toId), new Guid(Ids[j].ToString()), du.UserID, 0);
                            }
                            else
                            {
                                result = Bshare.ExecProcCustomerInfo(new Guid(pid), new Guid(toId), new Guid(Ids[j].ToString()), du.UserID, 0);
                            }
                        }
                    }
                    if (result.Trim() != "1")
                    {
                        this.ZXContext.Response.Write(result);
                        return;

                    }
                }
                this.ZXContext.Response.Write(result);
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }

        /// <summary>
        /// 保存问卷题目表 (问卷选择题目)
        /// </summary>
        /// <param name="Ids">题目ID集合</param>
        private void SaveTrQuestionnaireSubject(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string its = this.GetStringFromQueryString("its", "");
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                CrmCustomerShare tr = new CrmCustomerShare();
                bll.entity = tr;
                BTrQuestionnaireSubject bt = new BTrQuestionnaireSubject();
                IList<TrQuestionnaireSubject> list = bt.GetQuestionnaireSubjectInfoByQuestionnaireId(new Guid(pid));
                int listCount = 0;
                if (list != null)
                {
                    listCount = list.Count;

                }
                if (listCount >= int.Parse(its))
                {
                    this.ZXContext.Response.Write("问卷题目数已到达题目总数，不能再添加题目!");

                }
                else
                {
                    if (Ids.Length > int.Parse(its))
                    {
                        this.ZXContext.Response.Write("问卷题目数超过题目总数");
                    }
                    else
                    {
                        for (int j = 0; j < Ids.Length; j++)
                        {
                            DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                            string sql = string.Format("Exec sp_AddQuestionniareSubject '{0}','{1}','{2}','{3}','{4}'",
                                                         new Guid(pid), new Guid(Ids[j]), 0, 'Y', du.UserID);
                            bll.RunSqlCommand(sql);
                        }
                        this.ZXContext.Response.Write("1");
                    }
                }
            }
            catch
            {
                this.ZXContext.Response.Write("");
            }
        }
        private void Update()
        {
            string strEntity = this.GetStringFromQueryString("entity", "");
            string ids = this.GetStringFromQueryString("ids", "");
            string[] strIds = ids.Trim(',').Split(',');
            switch (strEntity.ToLower())
            {
                case "trindagatesubject":
                    UpdateTrIndagateSubject(strIds);
                    break;
                case "coursesum":
                    UpdateCourseSum();
                    break;
                case "datuser":
                    UserPwdSetting(strIds);
                    break;
                case "trquestionnaire":
                    UpdateQuestionniareSumup();
                    break;
                case "trquestionnairesubject":
                    UpdateQuestionnaireSubject(strIds);
                    break;
                case "crmmajorstudent":
                    UpdateCrmMajorStudent(strEntity);
                    break;
                case "v_crmmajorstudent":
                    SetManager();
                    break;
                case "v_crmmajorstudent1":
                    setSignIn();
                    break;;
            }
        }
        //签到
        private void setSignIn()
        {
            try
            {
                string pid = this.GetStringFromQueryString("id", "");
                iSun.BLL.Extend.BaseBussnies<CrmMajorStudent> bll = new iSun.BLL.Extend.BaseBussnies<CrmMajorStudent>();
                CrmMajorStudent newInstance = new CrmMajorStudent();
                bll.entity = newInstance;
                newInstance = bll.GetEntityById(pid) as CrmMajorStudent;
                newInstance.IsSignIn ="1";
                newInstance.SignIn = DateTime.Now;
                bll.Update(newInstance);
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }

        }
        //设置团长
        private void SetManager()
        {
            try
            {
                string pid = this.GetStringFromQueryString("id", "");
                iSun.BLL.Extend.BaseBussnies<CrmMajorStudent> bll = new iSun.BLL.Extend.BaseBussnies<CrmMajorStudent>();
                CrmMajorStudent newInstance = new CrmMajorStudent();
                bll.entity = newInstance;
                newInstance = bll.GetEntityById(pid) as CrmMajorStudent;
                //得到团号
                string GroupName = newInstance.GroupName;
                //根据团号找到该团的成员，并将其团长设置为当前选中学员
                List<CrmMajorStudent> list = (List<CrmMajorStudent>)bll.GetEntityListByCondition<CrmMajorStudent>("GroupName='" + GroupName+"'");
                foreach (CrmMajorStudent majorS in list)
                {
                    majorS.Colonel = new Guid(pid);
                    bll.Update(majorS);
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }

        }
        //更新大课学员
        private void UpdateCrmMajorStudent(string entityName)
        {
            try
            {
                string pid = this.GetStringFromQueryString("id", "");
                string strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
                CrmMajorStudent instance = (CrmMajorStudent)Globals.JSONtoObject(entityName, strJson);
                iSun.BLL.Extend.BaseBussnies<CrmMajorStudent> bll = new iSun.BLL.Extend.BaseBussnies<CrmMajorStudent>();
                 CrmMajorStudent newInstance=new CrmMajorStudent();
                bll.entity = newInstance;
                newInstance = bll.GetEntityById(pid) as CrmMajorStudent;
                newInstance.GroupName = instance.GroupName;
                newInstance.Assistance = instance.Assistance;
                newInstance.HouseType = instance.HouseType;
                newInstance.Explain = instance.Explain;
                bll.Update(newInstance);
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }


        }

        public void UpdateCourseSum()
        {
            string pid = this.GetStringFromQueryString("id", "");
            string couseSum = this.GetStringFromQueryString("GroupName", "");
            //BaseBussnies bbls = new BaseBussnies();
            //string sql = "update TrActivityCourse set CourseSumary='" + CSVHelper.FmSQL(couseSum) + "' where TrActivityCourseID='" + CSVHelper.FmSQL(pid) + "'";
            //if (bbls.RunSqlCommand(sql) != 0)
            //{
            //    this.ZXContext.Response.Write("1");
            //}
            //else
            //{
            //    this.ZXContext.Response.Write("0");
            //}
        }
        /// <summary>
        /// 更新调研题目表和调研表中信息
        /// </summary>
        /// <param name="ids">题目ID集合</param>
        private void UpdateTrIndagateSubject(string[] ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string answer = this.GetStringFromQueryString("answer", "");
            string[] strAnswer = answer.Split('#');
            string point = this.GetStringFromQueryString("point", "");
            string[] strPoint = point.Split('#');
            string SumPoint = this.GetStringFromQueryString("sumpoint", "");
            string Result = this.GetStringFromQueryString("result", "");
            if (SumPoint == "")
            {
                SumPoint = "0";
            }
            try
            {
                BaseBussnies bll = new BaseBussnies();
                if (ids.Length == 1 && ids[0] == "")
                {
                    string sql = string.Format("Exec sp_UpdateIndagateSubject '{0}','{1}','{2}','{3}','{4}','{5}',{6}",
                                     new Guid(pid), new Guid("00000000-0000-0000-0000-000000000000"), strAnswer[0],
                                     0, Convert.ToDecimal(SumPoint), Result, 0);
                    if (bll.RunSqlCommand(sql) != 0)
                    {
                        this.ZXContext.Response.Write("1");
                    }
                    else
                    {
                        this.ZXContext.Response.Write("0");
                    }
                }
                else
                {
                    for (int i = 0; i < ids.Length; i++)
                    {
                        string GetPoint = "0";
                        if (strPoint[i + 1] == "")
                        {
                            GetPoint = "0";
                        }
                        else
                        {
                            GetPoint = strPoint[i + 1];
                        }
                        string sql = string.Format("Exec sp_UpdateIndagateSubject '{0}','{1}','{2}','{3}','{4}','{5}',{6}",
                                     new Guid(pid), new Guid(ids[i]), strAnswer[i + 1],
                                     Convert.ToDecimal(GetPoint), Convert.ToDecimal(SumPoint), Result, 1);
                        bll.RunSqlCommand(sql);
                    }
                    this.ZXContext.Response.Write("1");
                }
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }
        /// <summary>
        /// 管理员设置用户密码
        /// </summary>
        /// <param name="ids">用户ID</param>
        private void UserPwdSetting(string[] ids)
        {
            string pwd = this.GetStringFromQueryString("news", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                bll.entity = new DatUser();
                string strSql = string.Format("update DatUser set Password='{0}' where UserID='{1}'", ExtendMethods.GetMd5Hash(pwd), ids[0]);
                if (bll.RunSqlCommand(strSql) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        ///  更新问卷总结【】
        /// </summary>
        private void UpdateQuestionniareSumup()
        {
            string strId = this.GetStringFromQueryString("id", "");
            string QSumup = this.GetStringFromQueryString("sumup", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                bll.entity = new TrQuestionnaire();
                string strSql = string.Format("update TrQuestionnaire set QSumup='{0}' where TrQuestionnaireID='{1}'", QSumup, strId);
                if (bll.RunSqlCommand(strSql) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 更新问卷题目信息【】
        /// </summary>
        private void UpdateQuestionnaireSubject(string[] ids)
        {
            string strId = this.GetStringFromQueryString("id", "");
            try
            {
                BaseBussnies bll = new BaseBussnies();
                bll.entity = new TrQuestionnaireSubject();
                string strSql = string.Format("update TrQuestionnaireSubject set Sequence='{0}',SubjectPoint='{1}',IsJumpOver='{2}' where TrQuestionnaireSubjectID='{3}'",
                                                ids[0], ids[1], ids[2], strId);
                if (bll.RunSqlCommand(strSql) == 1)
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write("0");
                }
            }
            catch
            {
                HttpContext.Current.Response.Write("0");
            }
        }
        /// <summary>
        /// 发送问卷
        /// </summary>
        /// <param name="Ids"></param>
        private void SaveTrSendQuestion(string[] Ids)
        {
            string pid = this.GetStringFromQueryString("id", "");
            string[] point = new string[0];
            try
            {
                BaseBussnies bll = new BaseBussnies();
                TrSendQuestion tr = new TrSendQuestion();
                bll.entity = tr;
                for (int j = 0; j < Ids.Length; j++)
                {
                    DatUser du = (DatUser)System.Web.HttpContext.Current.Session["User"];
                    string sql = "";
                    if (Ids.Length == 1 && Ids[0] == "11")  //集团所有人保存
                    {
                        sql = string.Format("Exec sp_AddSendQuestion '{0}','{1}','{2}',{3}",
                                                     new Guid(pid), "00000000-0000-0000-0000-000000000000", du.UserID, 1);
                    }
                    else if (Ids.Length == 1 && Ids[0] != "11")  //部门所有人保存
                    {
                        sql = string.Format("Exec sp_AddSendQuestion '{0}','{1}','{2}',{3}",
                                                     new Guid(pid), new Guid(Ids[0]), du.UserID, 2);
                    }
                    else   //逐个个人保存
                    {
                        sql = string.Format("Exec sp_AddSendQuestion '{0}','{1}','{2}',{3}",
                                                     new Guid(pid), new Guid(Ids[j]), du.UserID, 0);
                    }
                    bll.RunSqlCommand(sql);
                }
                this.ZXContext.Response.Write("1");
            }
            catch
            {
                this.ZXContext.Response.Write("0");
            }
        }

        private void Delete()
        {

        }
    }
}